package org.bp.ioc.config;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.bp.ioc.annotation.Action;
import org.bp.ioc.bean.Handler;
import org.bp.ioc.bean.Request;
import org.bp.ioc.utils.ObjectUtils;

/**
 * 获取请求与处理器之间的映射
 */
public class ControllerHelper {
    private static final Map<Request,Handler> ACTION_MAP = new HashMap<>();

    static {
        Set<Class<?>> classSet = ClassHelper.getControllerClassSet();
        if(ObjectUtils.isNotNull(classSet)){
            for (Class<?> clazz :classSet){
                Method[] methods = clazz.getDeclaredMethods();
                if(ObjectUtils.isNotNull(methods)){
                    for (Method method : methods){
                        if(method.isAnnotationPresent(Action.class)){
                            Action annotation = method.getAnnotation(Action.class);
                            //request : method path
                            //hander : class method
                            String url = annotation.value();
                            if(url.matches("\\w+:/\\w*")){
                                String[] split = url.split(":");
                                if(ObjectUtils.isNotNull(split) && split.length == 2){
                                    Request request = new Request(split[0],split[1]);
                                    Handler handler = new Handler(clazz,method);
                                    ACTION_MAP.put(request,handler);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public static Handler getHander(String requestMethod,String requestPath){
        Request request = new Request(requestMethod,requestPath);
        if(!ACTION_MAP.containsKey(request)){
            throw new RuntimeException("handler not fount");
        }
        return ACTION_MAP.get(request);
    }
}
